package cn.zhuama.user.interceptor;

import cn.zhuama.basic.attention.PreAuthorize;
import cn.zhuama.basic.util.JwtUtils;
import cn.zhuama.basic.util.LoginData;
import cn.zhuama.basic.util.Payload;
import cn.zhuama.basic.util.RsaUtils;
import cn.zhuama.system.mapper.PermissionMapper;
import cn.zhuama.user.domain.Logininfo;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String jwtToken = request.getHeader("Token");
        if (jwtToken!=null){
            /*JWTtoken解密*/
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
            /*2.2使用公钥解密token{   过期    }*/
            Payload<LoginData> payload = null;
            try {
                payload = JwtUtils.getInfoFromToken(jwtToken, publicKey, LoginData.class);
            } catch (ExpiredJwtException e) {//解密失败，说明jwttoken过期
                e.printStackTrace();
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"success\":false,\"message\":\"timeOut\"}");
                return false;
            }

            Logininfo logininfo = payload.getLoginData().getLogininfo();

            if(logininfo!=null){//登录还有效
                /*看门狗一样的，延长时间{jwt延时   把登录信息拿一遍，重新设置jwtToken  设置时间}*/
                //redisTemplate.opsForValue().set(token,loginInfoObject,30, TimeUnit.MINUTES);
                if(logininfo.getType().equals(Logininfo.WEB_USER)){//前台用户
                    return true;
                }else{//后台用户，验证权限
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    PreAuthorize annotation = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    /*如果注解不存在，接口是不需要权限就可以访问的*/
                    if(annotation==null){
                        return true;
                    }
                    /*当前访问接口，他需要的权限标识sn*/
                    String sn = annotation.value();
                    /*获取用户的所有权限*/
                    //List<String>  permissions =  permissdionMapper.selectPermissionByLoginInfoI(logininfo.getId());
                    List<String>  permissions =  payload.getLoginData().getPermissions();
                    if(!permissions.contains(sn)){//用户权限permissions  不包含sn  拦截
                        response.setContentType("application/json;charset=UTF-8");
                        response.getWriter().write("{\"success\":false,\"message\":\"noPermission\"}");
                        return false;
                    }
                }

                return true;//放行
            }
        }

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"success\":false,\"message\":\"noLogin\"}");
        return false;
    }
}
